package com.sunwayworld.basemodule.business.prefolder.io;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.basemodule.business.operationbatch.bean.LimsPreTaskSupplementBean;
import com.sunwayworld.basemodule.business.operationbatch.service.LimsPreTaskSupplementService;
import com.sunwayworld.basemodule.business.prefolder.bean.LimsPreFolderBean;
import com.sunwayworld.basemodule.business.prefolder.service.LimsPreFolderService;
import com.sunwayworld.framework.io.excel.utils.ExcelUtils;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component(value = "LimsPreTaskSupplementExportTemplate")
@GikamBean
public class LimsPreTaskSupplementExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    @Lazy
    private LimsPreFolderService limsPreFolderService;

    @Lazy
    @Autowired
    private LimsPreTaskSupplementService preTaskSupplementService;

    @Override
    public void initTemplateData(Path path, String id) {
        if (StringUtils.isEmpty(id)) {
            return;
        }
        List<LimsPreFolderBean> itemList = limsPreFolderService.selectListByFilter(SearchFilter.instance().match("operationBatch", id).filter(MatchPattern.EQ));
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);

            if (!itemList.isEmpty()) {
                // 获取批次补充信息
                List<LimsPreTaskSupplementBean> preTaskSupplementBeanList = preTaskSupplementService.selectListByFilter(SearchFilter.instance()
                        .match("preFolderId", itemList.stream().map(LimsPreFolderBean::getId).collect(Collectors.toList())).filter(MatchPattern.OR));
                itemList.forEach(preFolder -> {
                    List<LimsPreTaskSupplementBean> preTaskSupplementList = preTaskSupplementBeanList.stream().filter(e -> e.getPreFolderId().equals(preFolder.getId())).collect(Collectors.toList());
                    if (!preTaskSupplementList.isEmpty()) {
                        Map<String, String> fieldInfo = new HashMap<>();
                        preTaskSupplementList.forEach(supplement -> {
                            preFolder.setExt$Item(supplement.getFieldName(), supplement.getFieldValue());
                            fieldInfo.put(supplement.getFieldName(), supplement.getFieldValue());
                        });
                        preFolder.setExt$Item("supplementinfo", JSONObject.toJSONString(fieldInfo, SerializerFeature.WriteMapNullValue));
                    }
                });
                addExtColumns(sheet, workBook, preTaskSupplementBeanList);
                addInfo(sheet, workBook, itemList);
            }

            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void addExtColumns(Sheet sheet, Workbook wb, List<LimsPreTaskSupplementBean> itemList) {
        CellStyle centerCellStyle = ExcelUtils.getCenterCellStyle(wb);
        centerCellStyle.setBorderTop(BorderStyle.THIN);
        centerCellStyle.setBorderBottom(BorderStyle.THIN);
        //创建此表的HSSFPatriarch实例
        Drawing<?> patriarch = sheet.createDrawingPatriarch();

        Row titleRow = sheet.getRow(0);
        int colNum = titleRow.getPhysicalNumberOfCells();
        List<String> fieldNames = itemList.stream().map(LimsPreTaskSupplementBean::getFieldName).distinct().collect(Collectors.toList());
        for (int i = 0; i < fieldNames.size(); i++) {
            Cell newTitleCell = titleRow.createCell(colNum + i);
            String fieldName = fieldNames.get(i);
            itemList.stream().filter(t -> t.getFieldName().equalsIgnoreCase(fieldName)).findAny().ifPresent(t -> {
                if (!StringUtils.isBlank(t.getUnit())) {
                    newTitleCell.setCellValue(t.getFieldName().concat("(").concat(t.getUnit()).concat(")"));
                } else {
                    newTitleCell.setCellValue(t.getFieldName());
                }
                addComment(patriarch, newTitleCell, fieldName);
            });
            newTitleCell.setCellStyle(centerCellStyle);
        }
    }

    private void addInfo(Sheet sheet, Workbook wb, List<LimsPreFolderBean> itemList) {
        Row titleRow = sheet.getRow(0);
        int colNum = titleRow.getPhysicalNumberOfCells();
        int firstRow = 1;

        CellStyle centerCellStyle = ExcelUtils.getCenterCellStyle(wb);
        centerCellStyle.setBorderTop(BorderStyle.THIN);
        centerCellStyle.setBorderBottom(BorderStyle.THIN);

        for (int i = 0; i < itemList.size(); i++) {
            LimsPreFolderBean bean = itemList.get(i);
            Row row = sheet.createRow(i + firstRow);
            for (int j = 1; j < colNum; j++) {
                try {
                    String column = titleRow.getCell(j).getCellComment().getString().getString();
                    Object v = BeanUtils.getPropertyValue(bean, column);
                    Cell cell = row.createCell(j);
                    if (v != null) {
                        cell.setCellValue(v.toString());
                    }
                    cell.setCellStyle(centerCellStyle);
                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 设置单元格注释
     *
     * @param patriarch
     * @param cell
     */
    public void addComment(Drawing patriarch, Cell cell, String note) {

        Comment comment = patriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 1, 2, (short) 4, 4));

        comment.setString(new XSSFRichTextString(note));

        cell.setCellComment(comment);

    }
}
